package ichubetcd

import (
	"context"
	"fmt"
	"gitee.com/ichub/goconfig/common/base/baseutils/jsonutils"
	"github.com/coreos/etcd/clientv3"
	"time"
)

type EtcdClientV3 struct {
	EtcdHosts []string

	PreKey string

	cli *clientv3.Client `json:"-"`
}

func NewEtcdClientV3(etcdHosts []string, pkeys ...string) *EtcdClientV3 {
	var pkey = "Etcd:Cfg"
	if len(pkeys) > 0 {
		pkey = pkeys[0]
	}
	return &EtcdClientV3{
		PreKey:    pkey,
		EtcdHosts: etcdHosts,
	}
}

func (client *EtcdClientV3) String() string {
	s, _ := jsonutils.ToJson(client)
	return s
}

func (client *EtcdClientV3) Init() error {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   client.EtcdHosts,
		DialTimeout: 5 * time.Second,
	})
	fmt.Println("EtcdHosts=", client.String())
	if err != nil {
		fmt.Printf("connect to etcd failed, err:%v\n", err)
		return err
	}
	client.cli = cli
	//defer client.cli.Close()

	return nil
}

func (client *EtcdClientV3) makeKey(key string) string {
	return client.PreKey + ":" + key
}
func (client *EtcdClientV3) Set(key string, value string) {
	cli := client.cli
	// put
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err := cli.Put(ctx, client.makeKey(key), value)

	cancel()
	if err != nil {
		fmt.Printf("put to etcd failed, err:%v\n", err)
		return
	}
}

func (client *EtcdClientV3) Get(key string) (string, error) {
	cli := client.cli
	resp, err := cli.Get(context.Background(), client.makeKey(key))
	var value = resp.Kvs[0].Value
	fmt.Println("etcd value=", string(value))
	//cancel()
	if err != nil {
		fmt.Printf("get from etcd failed, err:%v\n", err)
		return "", err
	}
	return string(value), nil
}
func (client *EtcdClientV3) Delete(key string) error {
	cli := client.cli
	resp, err := cli.Delete(context.Background(), client.makeKey(key))

	fmt.Println("etcd value=", resp)
	//cancel()
	if err != nil {
		fmt.Printf("get from etcd failed, err:%v\n", err)
		return err
	}
	return nil
}
